package com.whyl.eems.exception;

import com.whyl.eems.common.exception.BaseException;
import com.whyl.eems.common.exception.ConstantExceptionEnums;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 作者：阿坤
 * 创建时间：11:28 2019/8/19
 * 功能描述：
 */
@ControllerAdvice
public class CommonExceptionHandler {

    /**
     * 拦截Exception类的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String,Object> exceptionHandler(Exception e){
        Map<String,Object> result = new HashMap<String,Object>();
        if( e instanceof BaseException){
            BaseException e1 = (BaseException) e;
            ConstantExceptionEnums constantExceptionEnums = e1.getConstantExceptionEnums();
            result.put("code", constantExceptionEnums.getCode());
            result.put("mgs", constantExceptionEnums.getMessage());
            return result;
        }else{
            result.put("code", 500);
            result.put("mgs", "系统异常！");
            //正常开发中，可创建一个统一响应实体，如CommonResp
            return result;
        }
    }
}
